<template>
  <div class="video">
    <video ref="videoElement" controls autoplay muted v-if="!error"></video>
    <div class="error" v-else>视频播放错误！</div>
  </div>
</template>
 
<script>
import flvjs from "flv.js";
export default {
  name: "flvVideo",
  data() {
    return {
      url:'/live/livestream.flv',
      flvPlayer: "",
      error: false,
    };
  },
  mounted() {
    
    this.$nextTick(() => {
      console.log('url:',window.config.apiUrl+this.url);
      this.init(window.config.apiUrl+this.url)
    });
  },
  methods: {
    init(source) {
      if (flvjs.isSupported()) {
 
        this.flvPlayer = flvjs.createPlayer(
          {
            type: 'flv',						//flv格式
            isLive: true,					//直播模式
            hasVideo: true,				//视频开启
            url: source,
            // hasAudio: true, 			//音频开启
            enableStashBuffer: false, //设置启用播放缓存，只在直播起作用（降低延迟）。关闭IO隐藏缓冲区
            // enableWorker: true, 	//浏览器端开启flv.js的worker,多进程运行flv.js。不启用分离线程
            // reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
            // autoCleanupSourceBuffer: true, //自动清除缓存
          }
        );
 
        this.flvPlayer.attachMediaElement(this.$refs.videoElement);
        this.flvPlayer.load();
        this.flvPlayer.play();
 
        // 加载完成
        this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
          this.error = false;
        });
 
        // 加载失败
        this.flvPlayer.on(flvjs.Events.ERROR, () => {
          this.error = true;
        },(error) => {
          console.log(error);
        });
 
      } else {
        this.error = true;
      }
    },
    // 销毁
    detachMediaElement() {
      this.flvPlayer.pause();
      this.flvPlayer.unload();
      this.flvPlayer.detachMediaElement();
      this.flvPlayer.destroy();
      this.flvPlayer = "";
    },
    // 播放
    play () {
      this.flvPlayer.play();
    }
  },
  watch: {
    // 更换流
    url() {
      this.error = false;
      this.flvPlayer == "" ? "" : this.detachMediaElement(); // 切换流之前，判断之前的流是否销毁
      this.init(this.url);
    },
 
    // 开关值
    destroy() {
      if (this.destroy) {
        this.init(this.url);
      } else {
        this.flvPlayer == "" ? "" : this.detachMediaElement();
      }
    },
  },
  beforeDestroy() {
    this.detachMediaElement();
  },
};
</script>
 
<style scoped>
.video {
  position: relative;
  height: 100%;
}
video {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
.error {
  position: absolute;
  top: 30%;
  left: 50%;
  margin-left: -120px;
  text-align: center;
  color: #00fdff;
  font-weight: bold;
  font-size:50px;
}
 
</style>